# codingL utf-8
import hashlib
import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

from settings import LOG_DIR, REMOTE_DRIVER_URL



def tail_f(filename):
    path = os.path.join(LOG_DIR, filename)
    ensure_file_exists(path)

    with open(path, 'r', encoding="utf-8") as file:
        # 移动到文件末尾
        file.seek(0, 2)  # SEEK_END
        while True:
            line = file.readline()
            if not line:
                # 等待新数据
                time.sleep(1)
                continue
            yield line


def ensure_file_exists(filepath):
    # 检查文件是否存在
    if not os.path.exists(filepath):
        # 如果文件不存在，创建它
        with open(filepath, 'w', encoding="utf-8") as file:
            file.write('')


def get_webdriver(user_data=None):
    """
        install webdriver
    :param user_data:
    :return: webdriver object
    """
    chrome_options = Options()
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--remote-debugging-port=9222")
    chrome_options.add_argument("--disable-dev-shm-usage")
    if user_data:
        # 指定用户数据目录
        chrome_options.add_argument(
            f"--user-data-dir={user_data}")
        # 指定配置文件目录
        chrome_options.add_argument(
            f"--profile-directory={user_data}/Default")

    # 创建远程 Chrome 驱动
    driver = webdriver.Remote(
        command_executor=REMOTE_DRIVER_URL,
        options=chrome_options,
    )
    return driver


def connect_running_driver():
    # 创建 ChromeOptions 对象
    chrome_options = Options()
    # 连接到已打开的 Chrome 实例
    chrome_options.add_experimental_option("debuggerAddress",
                                           "localhost:9222")
    # 连接到 Selenium Grid
    driver = webdriver.Remote(
        command_executor=REMOTE_DRIVER_URL,
        options=chrome_options
    )
    return driver


def md5_encrypt(text):
    # 创建md5对象
    md = hashlib.md5()
    if type(text) == str:
        # 更新hash对象的值
        md.update(text.encode("utf-8"))
    else:
        md.update(text)
    # return 32位加密串  16位: md.hexdigest()[8:-8]
    res = {"32": md.hexdigest(), "16": md.hexdigest()[8:-8]}
    return res
